package com.swh.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @Author: swh
 * @Description:
 * @Date: 2021/1/18 12:19
 * @Version: 1.0
 */
@Component
public class SmsUtil {

    @Autowired
    private  Environment environment;

    @Test
    public void main() {
        sendSms("13926729084","1234");
    }

    public  void sendSms(String phone,String code){
        String id = environment.getProperty("aliyun.sms.accessKeyId");
        String accessKeySecret = environment.getProperty("aliyun.sms.accessKeySecret");
        String templateCode = environment.getProperty("aliyun.sms.template_code");
        String signName = environment.getProperty("aliyun.sms.sign_name");


//        System.out.println(id+"--------"+accessKeySecret);


        //默认配置项
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", id, accessKeySecret);
        //客户端对象
        IAcsClient client = new DefaultAcsClient(profile);

        //请求 参数设置
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);

        //阿里服务器的配置
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");


        request.putQueryParameter("PhoneNumbers", phone);   //手机号
        request.putQueryParameter("SignName", signName);//签名名称
        request.putQueryParameter("TemplateCode", templateCode);//模版CODE
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//请JSON格式字符串为模板变量赋值
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        }catch (ClientException e) {
            e.printStackTrace();
        }
    }

}
